package com.yaowen.myapplication;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * Created by HelloWorld on 2015/9/21.
 */

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class LeftFragment extends Fragment {
    /** Acitivity要实现这个接口，这样Fragment和Activity就可以共享事件触发的资源了 */
   public interface MyListener{
        public void showMessage(int index);
    }
    private MyListener myListener;
    private Button firstButton,secondButton,thirdButton;
    /** Fragment第一次附属于Activity时调用,在onCreate之前调用 */
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Log.d("LeftFragment", "onAttach");
        myListener= (MyListener) activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("LeftFragment", "onCreate");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d("LeftFragment", "onCreateView");
        return inflater.inflate(R.layout.fragment_left,container,false);
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("LeftFragment", "onResume");
        firstButton= (Button) getActivity().findViewById(R.id.first_button);
        secondButton= (Button) getActivity().findViewById(R.id.second_button);
        thirdButton= (Button) getActivity().findViewById(R.id.third_button);
        MyButtonClickListener buttonClickListener=new MyButtonClickListener();
        firstButton.setOnClickListener(buttonClickListener);
        secondButton.setOnClickListener(buttonClickListener);
        thirdButton.setOnClickListener(buttonClickListener);
    }
    /** 按钮的监听器 */
    public class MyButtonClickListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            Button button= (Button) v;
            if (button==firstButton){
                myListener.showMessage(1);
            }
            if (button==secondButton){
                myListener.showMessage(2);
            }
            if (button==thirdButton){
                myListener.showMessage(3);
            }
        }
    }
}
